import React, { PureComponent, StrictMode } from "react"
import {
  CSSTransition,
  SwitchTransition,
  TransitionGroup
} from "react-transition-group"
import "./style.css"

export default class CpnTransitionGroup extends PureComponent {
  constructor() {
    super()
    this.state = {
      bookList: [
        { name: "你不知道的JS", price: 99, id: 0 },
        { name: "JS高级程序设计", price: 23, id: 1 }
      ]
    }
  }

  addBookItem(length) {
    const bookItem = { name: "你不知道的JS" + length, price: 99, id: length }
    const bookList = [...this.state.bookList]
    bookList.push(bookItem)
    this.setState({
      bookList
    })
  }

  removeBookItem(id) {
    const bookList = [...this.state.bookList].filter((book) => book.id !== id)
    this.setState({
      bookList
    })
  }

  render() {
    const { bookList } = this.state
    return (
      <div style={{ width: "400px" }}>
        <h3>书籍列表：</h3>
        {/*component指定渲染元素为ul元素*/}
        <TransitionGroup component="ul">
          {bookList.map((book) => (
            // 肯定要CSSTransition 因为这才是过度动画组件 而且必备的key classNames timeout不能少
            <CSSTransition key={book.id} classNames="book" timeout={1000}>
              <li style={{ margin: "10px 0" }}>
                <span style={{ width: "150px", display: "inline-block" }}>
                  {book.name}
                </span>
                <button
                  onClick={() => {
                    this.removeBookItem(book.id)
                  }}
                >
                  移除
                </button>
              </li>
            </CSSTransition>
          ))}
        </TransitionGroup>
        <button onClick={() => this.addBookItem(bookList.length)}>
          添加一本书
        </button>
      </div>
    )
  }
}
